package com.share.dymamic.controller;

import java.util.List;

import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

import com.share.dymamic.annotion.DBWrite;
import com.share.dymamic.entity.Entity;
import com.share.dymamic.service.EntityService;

/** 
 *
* @author weigen.ye 
* @date 创建时间：2016年9月23日 上午11:05:46 
*
*/
@Controller
@RequestMapping("/entity")
public class OperationController extends BasicController{
	
    @Autowired
    private EntityService entityService;

    @RequestMapping(value = "/")
    public ModelAndView list(HttpServletRequest request){
        ModelAndView mv = new ModelAndView("/list");
        String ope_result = request.getParameter(OPE_RESULT);
        if(org.apache.commons.lang.StringUtils.isNotBlank(ope_result)){
            mv.addObject(OPE_RESULT,ope_result + "," + System.currentTimeMillis());
        }
        try{
            List<Entity> entities = this.entityService.select();
            mv.addObject("entities",entities);
        }catch (Exception e){
            logger.error("查询操作失败",e);
        }
        return mv;
    }
    
    @DBWrite
    @RequestMapping(value = "/toAdd")
    public ModelAndView toAdd(Long id){
        ModelAndView mv = new ModelAndView("/add");
        return mv;
    }

    @DBWrite
    @RequestMapping(value = "/add")
    @Transactional(rollbackFor=RuntimeException.class)
    public ModelAndView add(Entity entity,HttpServletRequest request){
    	ModelAndView view = new ModelAndView("redirect:/entity/");
        String result = RESULT_ERROR;
        try{
        	entityService.insert(entity);
            result = RESULT_ADD_SUCCESS;
//            throw new RuntimeException("测试切换数据源为只写数据源时，增加后发现异常能否回滚！");
        }catch (Exception e){
            logger.error("添加信息失败",e);
        }
        view.addObject(OPE_RESULT, result);
        return view;
    }

    @DBWrite
    @RequestMapping(value = "/toEdit")
    public ModelAndView toEdit(Integer id){
        ModelAndView mv = new ModelAndView("/edit");
        try{
            Entity entity = entityService.selectByKey(id);
            mv.addObject("entity",entity);
        }catch (Exception e){
            logger.error("不存在要修改的信息",e);
        }
        return mv;
    }
    
    @DBWrite
    @RequestMapping(value = "/edit")
    public ModelAndView edit(Entity entity){
    	ModelAndView view = new ModelAndView("redirect:/entity/");
        String result = RESULT_ERROR;
        try{
        	entityService.update(entity.getId(),entity.getStatus());
            result = RESULT_EDIT_SUCCESS;
        }catch (Exception e){
            logger.error("修改信息失败",e);
        }
        view.addObject(OPE_RESULT, result);
        return view;
    }

}
